<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>{{ share_info.share_name }}</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap.min.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap-table.min.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/jquery.growl.css') }}">
    <style>
        .tool {
            display: flex;
            justify-content: space-between;
            margin: 5px;
        }

        .file-path {
            font-size: 16px;
            color: #000000;
        }

        .remove {
            margin-left: 5px;
        }
    </style>
</head>
<body>
{#导航#}
<nav class="navbar navbar-default">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                    data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="/index">阿里云盘下载</a>
            <a class="navbar-brand" href="/ng" target="_blank">AriaNg</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">

            </ul>
            <ul class="nav navbar-nav navbar-right">
                {% if user %}
                    <li><p class="navbar-text">{{ user.user_name }}</p></li>
                    <li><p class="navbar-text">{{ user.nick_name }}</p></li>
                {% else %}
                    <li><a href="javascript:void(0);">扫一扫登录</a></li>
                {% endif %}
            </ul>
        </div>
    </div>
</nav>
<div class="tool">
    <div class="file-path">/{{ share_info.share_name }}</div>
    <button class="btn btn-primary" onclick="initTable()">刷新</button>
</div>

<!-- 设置别名 -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">新增分享地址</h4>
            </div>
            <div class="modal-body">
                <form>
                    <div class="form-group">
                        <label for="recipient-name" class="control-label">别名：</label>
                        <input type="text" id="alias" class="form-control"/>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="updateAlias()">保存</button>
            </div>
        </div>
    </div>
</div>

<table id="file-table">
</table>
<script src="{{ url_for('static', filename='js/jquery.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/bootstrap3-typeahead.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/bootstrap-table.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/bootstrap-table-zh-CN.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/jquery.growl.js') }}"></script>
<script>
    let parent_file_id = 'root'
    let file_path = []
    let back = []
    $(function () {
        initTable()
    })

    function initTable() {
        $("#file-table").bootstrapTable('destroy').bootstrapTable({
            method: "get",
            url: "get_file_list",
            queryParams: function (params) {
                return {
                    parent_file_id: parent_file_id,
                    share_id: '{{ share_info.share_id }}'
                };
            },
            onLoadSuccess: function (res) {
                $("#file-table").bootstrapTable('prepend', {name: '返回', type: 'back'})
            },
            onLoadError: function (err) {  //加载失败时执行
                console.log(err);
            },
            columns: [
                {
                    field: 'name', title: '文件名称', formatter: function (value, row) {
                        if (row.type === 'back') {
                            return `<button type="button" class="back btn btn-warning btn-sm">${value}</button>`
                        } else if (row.type === 'folder') {
                            if (row.alias) {
                                return `<a href="javascript:void(0);" class="file-name">${value}</a><span class="help-block">${row.alias}</span>`
                            }
                            return `<a href="javascript:void(0);" class="file-name">${value}</a>`
                        } else {
                            return value
                        }
                    },
                    events: window.operateEvents,
                },
                {
                    field: 'size', title: '文件大小', formatter: function (value) {
                        if (value) return change(value);
                    }
                },
                {
                    field: 'created_at', title: '创建时间', formatter: function (value) {
                        let d = new Date(value);
                        return value == null ? null : dateFormat("YYYY-mm-dd HH:MM:SS", d);
                    }
                },
                {
                    field: 'file_id',
                    title: '操作',
                    align: 'center',
                    width: 160,
                    events: window.operateEvents,
                    formatter: function (value, row) {
                        if (row.type === 'file') {
                            if (row.download_status === 0) return `<button type="button"  class="btn btn-primary download" >远程下载</button>`
                            if (row.download_status === 1) return `<button type="button"  class="btn btn-success" disabled>下载中</button><button type="button"  class="btn btn-danger btn-xs remove" >删除</button>`
                            if (row.download_status === 2) return `<button type="button"  class="btn btn-success" disabled>成功</button><button type="button"  class="btn btn-danger btn-xs remove" >删除</button>`
                        } else if (row.type === 'folder') {
                            return `<button type="button"  class="btn btn-primary alias" >设置别名</button>`
                        }
                    }
                }
            ]
        });

    }

    window.operateEvents = {
        'click .back': function (e, value, row) {
            file_path.pop()
            if (file_path.length > 0) $('.file-path').html('/' + file_path.join('/') + '/')
            if (parent_file_id === 'root') {
                window.history.back();
            } else {
                parent_file_id = back.pop()
                initTable()
            }
        },
        'click .file-name': function (e, value, row) {
            file_path.push(value)
            $('.file-path').html('/' + file_path.join('/') + '/')
            back.push(parent_file_id)
            parent_file_id = row.file_id
            initTable()
        },
        'click .download': function (e, value, row) {
            $(e.target).html('下载中').removeClass('download btn-primary').addClass('btn-success').attr("disabled", "disabled");
            $.post('/download', {
                share_id: row.share_id,
                file_id: row.file_id
            }, function (res) {
                $(e.target).html('成功')
            });
        },
        'click .remove': function (e, value, row) {
            $.post('/remove_file', {
                share_id: row.share_id,
                file_id: row.file_id
            }, function (res) {
                if (res.error !== '') {
                    $.growl.error({title: "错误提醒", message: res.error});
                    return;
                }
                $.growl.notice({title: "成功提醒", message: '移除成功'});
                $("#file-table").bootstrapTable('remove', {
                    field: 'file_id',
                    values: row.file_id
                })
            });
        },
        'click .alias': function (e, value, row) {
            let $alias = $('#alias');
            $('#myModal').modal('show');
            $alias.val(row.alias != null ? row.alias : row.name)
            $alias.data('file_id', row.file_id)
        }
    }

    function updateAlias() {
        let $alias = $('#alias')
        if ($alias.val() === '') {
            $.growl.error({title: "错误提示", message: "请输入别名"});
            return;
        }
        $.post('/update_alias', {file_id: $alias.data('file_id'), alias: $alias.val()}, function (res) {
            $alias.val("");
            $.growl.notice({title: "成功提醒", message: '设置别名成功'});
            $('#myModal').modal('toggle');
            initTable()
        });
    }

    function dateFormat(fmt, date) {
        let ret;
        const opt = {
            "Y+": date.getFullYear().toString(),        // 年
            "m+": (date.getMonth() + 1).toString(),     // 月
            "d+": date.getDate().toString(),            // 日
            "H+": date.getHours().toString(),           // 时
            "M+": date.getMinutes().toString(),         // 分
            "S+": date.getSeconds().toString()          // 秒
            // 有其他格式化字符需求可以继续添加，必须转化成字符串
        };
        for (let k in opt) {
            ret = new RegExp("(" + k + ")").exec(fmt);
            if (ret) {
                fmt = fmt.replace(ret[1], (ret[1].length === 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
            }
        }
        return fmt;
    }

    function change(limit) {
        let size = "";
        if (limit < 0.1 * 1024) {                            //小于0.1KB，则转化成B
            size = limit.toFixed(2) + "B"
        } else if (limit < 0.1 * 1024 * 1024) {            //小于0.1MB，则转化成KB
            size = (limit / 1024).toFixed(2) + "KB"
        } else if (limit < 0.1 * 1024 * 1024 * 1024) {        //小于0.1GB，则转化成MB
            size = (limit / (1024 * 1024)).toFixed(2) + "MB"
        } else {                                            //其他转化成GB
            size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB"
        }

        const sizeStr = size + "";                        //转成字符串
        const index = sizeStr.indexOf(".");                    //获取小数点处的索引
        const dou = sizeStr.substr(index + 1, 2);            //获取小数点后两位的值
        if (dou === "00") {                                //判断后两位是否为00，如果是则删除00
            return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
        }
        return size;
    }
</script>
</body>
</html>